package com.weixin.demo.config;

import com.weixin.demo.constants.CommonConstant;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.List;

/**
 * @desc rest模板配置
 */
@Configuration
public class RestTemplateConfig {

    /**
     * @desc: 获取RestTemplate
     */
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
        RestTemplate restTemplate = new RestTemplate(factory);
        List<HttpMessageConverter<?>> messageConverts = restTemplate.getMessageConverters();
        for (HttpMessageConverter messageConverter : messageConverts) {
            if (messageConverter instanceof StringHttpMessageConverter) {
                StringHttpMessageConverter stringHttpMessageConverter = (StringHttpMessageConverter) messageConverter;
                stringHttpMessageConverter.setDefaultCharset(Charset.forName("UTF-8"));
            }
        }
        return restTemplate;
    }

    /**
     * @desc: 工厂
     */
    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(CommonConstant.INTERFACE_TIMEOUT_TIME_LENGTH);
        factory.setConnectTimeout(CommonConstant.INTERFACE_TIMEOUT_TIME_LENGTH);
        return factory;
    }

}
